﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;

namespace MBBStoreClient
{
    public partial class frmInventoryModule : Form
    {
        UnityProcessor proc = new UnityProcessor();
        UnityScript itemBuf = new UnityScript("SAVEBUFFER", new object[] { "fBarcode", "fDescription", "fQty" });
        string itemDesc = "";
        
        Threader t = new Threader();
        DataTable tblproducts = new DataTable();

        public frmInventoryModule()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }
        private void InitializeForm()
        {
            lblInst.Text = "1. Set the quantity.\r\n" +
                "2. Enter the barcode on the field provided.\r\n" +
                "3. Press enter or click add.(Automatic when using barcode reader)\r\n"+
                "4. Click the 'Save Data to File' button to save the inventory data.";

            itemBuf.Desc_FileTitle = "tblproductstockwhole";
            itemBuf.Desc_MetaData = "COLLECTED INVENTORY DATA";

            grpEntry.Enabled = false;
            tabTable.Enabled = false;
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);
            btnSet.Click += new EventHandler(btnSet_Click);
            btnSearch.Click += new EventHandler(btnSearch_Click);
            btnAdd.Click += new EventHandler(btnAdd_Click);
            btnSave.Click += new EventHandler(btnSave_Click);
            btnLoadData.Click += new EventHandler(btnLoadData_Click);

            txtSearch.KeyUp += new KeyEventHandler(txtSearch_KeyUp);
            grdResult.DoubleClick += new EventHandler(grdResult_DoubleClick);
            txtBarcode.KeyPress += new KeyPressEventHandler(txtBarcode_KeyPress);

        }

        void txtBarcode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                btnAdd_Click(null, null);
            }
        }

        void btnLoadData_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Open Saved Inventory Data";
            dlg.Filter = "All|*.*|Save Inventory Data|*.sid";
            dlg.FilterIndex = 2;
            dlg.AddExtension = true;
            dlg.CheckPathExists = true;
            dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                States(false);
                itemBuf.Script_Clear();
                itemBuf.Script_Add(Script.PROC_NAME, "READBUFFER");
                itemBuf.Script_Add(Script.LFFPU_READ, dlg.FileName, "elayorbulc");
                proc.Run(itemBuf);
            } 
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Title = "Saved Inventory Data";
            dlg.Filter = "All|*.*|Saved Inventory Data|*.sid";
            dlg.FilterIndex = 2;
            dlg.AddExtension = true;
            dlg.CheckPathExists = true;
            dlg.OverwritePrompt = true;
            dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                States(false);
                itemBuf.Script_Clear();
                itemBuf.Script_Add(Script.PROC_NAME, "SAVEBUFFER");
                itemBuf.Script_Add(Script.LFFPU_WRITE, dlg.FileName, "elayorbulc");
                proc.Run(itemBuf);
            }
        }

        void btnAdd_Click(object sender, EventArgs e)
        {
            if (txtQty.Value != 0)
            {
                DataRow[] dr = tblproducts.Select("fBarcode='" + txtBarcode.Text + "'");
                if (dr.Length == 1)
                {
                    if (dr[0][0].ToString().Length == 0)
                    {
                        MessageBox.Show("Barcode is not recognized.", "Add Item", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    UnityElement item = new UnityElement(itemBuf.Desc_Fields());
                    item.Data_SetField(0, txtBarcode.Text);
                    item.Data_SetField(1, dr[0][1].ToString());
                    item.Data_SetField(2, txtQty.Value);

                    itemBuf.Data_AddNew(item);

                    grdInventory.DataSource = itemBuf.ToDataTable();
                    grdInventory.Columns[0].HeaderText = "Barcode";
                    grdInventory.Columns[1].HeaderText = "Description";
                    grdInventory.Columns[2].HeaderText = "Qty";

                    grdInventory.Columns[0].Width = (grdInventory.Width * 20) / 100;
                    grdInventory.Columns[1].Width = (grdInventory.Width * 60) / 100;
                    grdInventory.Columns[2].Width = (grdInventory.Width * 15) / 100;

                    txtBarcode.Text = "";
                    txtBarcode.Focus();
                }
                else
                {
                    MessageBox.Show("Barcode is not recognized.", "Add Item", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Please enter a valid value for the quantity.", "Add Item", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void grdResult_DoubleClick(object sender, EventArgs e)
        {
            if (grdResult.SelectedRows.Count > 0)
            {
                txtBarcode.Text = grdResult.SelectedRows[0].Cells[0].Value.ToString();
                itemDesc = grdResult.SelectedRows[0].Cells[1].Value.ToString();
                txtBarcode.Focus();
                txtBarcode.SelectionStart = txtBarcode.Text.Length;
            }
        }

        void txtSearch_KeyUp(object sender, KeyEventArgs e)
        {
            btnSearch_Click(null, null);
        }

        void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                DataRow[] res = tblproducts.Select("fDescription LIKE '%" + txtSearch.Text + "%' OR fSupplier LIKE '%" + txtSearch.Text + "%'", "fSupplier ASC, fBarcode ASC");
                DataTable searchRes = tblproducts.Clone();
                int limit = res.Length;
                if (limit > 100) limit = 100;
                for (int i = 0; i < limit; i++)
                {
                    searchRes.ImportRow(res[i]);
                }
                grdResult.DataSource = searchRes;
                string[] colName = { "Barcode", "Description", "Supplier", "Unit", "Content" };
                for (int i = 0; i < grdResult.Columns.Count; i++) grdResult.Columns[i].HeaderText = colName[i];
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lookup data is not recognized. Please export another product data and reload.", "Search Item", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void btnSet_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Open Exported Product Data";
            dlg.Filter = "All|*.*|Exported Products Data|*.epd";
            dlg.FilterIndex = 2;
            dlg.AddExtension = true;
            dlg.CheckPathExists = true;
            dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                States(false);
                UnityScript getProd = new UnityScript("GETPROD", 5);
                getProd.Script_Add(Script.LFFPU_READ, dlg.FileName, "elayorbulc");
                proc.Run(getProd);
            } 
        }

        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(desc, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            });
        }
        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "GETPROD":
                        UnityScript getProd;
                        proc.Data_Fetch(out getProd);
                        tblproducts = getProd.ToDataTable();
                        lblLookUpFile.Text = getProd.Desc_LocalFile;
                        States(true);
                        break;

                    case "SAVEBUFFER":
                        States(true);
                        break;

                    case "READBUFFER":
                        proc.Data_Fetch(out itemBuf);
                        States(true);

                        grdInventory.DataSource = itemBuf.ToDataTable();
                        grdInventory.Columns[0].HeaderText = "Barcode";
                        grdInventory.Columns[1].HeaderText = "Description";
                        grdInventory.Columns[2].HeaderText = "Qty";

                        grdInventory.Columns[0].Width = (grdInventory.Width * 20) / 100;
                        grdInventory.Columns[1].Width = (grdInventory.Width * 60) / 100;
                        grdInventory.Columns[2].Width = (grdInventory.Width * 15) / 100;
                        break;
                }
            });
        }
        void States(bool state)
        {
            grpEntry.Enabled = state;
            grpLookUp.Enabled = state;
            tabTable.Enabled = state;
        }
    }
}
